package com.sys.service.impl;

import com.sys.base.UserBean;
import com.sys.dao.model.GftUserInfo;
import com.sys.dao.model.LogInfo;
import com.sys.dao.model.LogSettings;
import com.sys.dao.model.RightSettings;
import com.sys.plat.bean.PageBean;
import com.sys.plat.service.base.BaseServiceImpl;
import com.sys.service.LogInfoService;
import com.sys.system.Constants;
import com.sys.web.util.RegExpUtils;
import com.sys.web.util.SystemUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;


public class LogInfoServiceImpl extends BaseServiceImpl implements
        LogInfoService {

	public void listLogInfo(PageBean pb) {
		pb.setHql("FROM LogInfo");
		this.page(pb);
	}

	public LogInfo view(LogInfo logInfo) {
		return (LogInfo) this.dao.getObject(LogInfo.class, logInfo.getId());
	}

	public int delete(String[] ids) {
		return delObject(ids, LogInfo.class);
	}

	@SuppressWarnings("unchecked")
	public Map<String, LogSettings> initLogSettings() {
		Map<String, LogSettings> map = new HashMap<String, LogSettings>();
		StringBuffer buf = new StringBuffer();
		buf.append("FROM LogSettings WHERE status=?");
		for (Object obj : this.dao.listByHql(buf.toString(),
				Constants.STATUS_YES)) {
			LogSettings logSettings = (LogSettings) obj;
			map.put(logSettings.getUrl() + logSettings.getOp(), logSettings);
		}
		return map;
	}

	@SuppressWarnings("unchecked")
	public void insertLogInfo(HttpServletRequest request, HttpSession session) {
		String uri = request.getRequestURI().replaceFirst(
				request.getContextPath(), "");
		String op = request.getParameter("op");
		Map<String, LogSettings> logSetsMap = (Map) session.getServletContext()
				.getAttribute(Constants.SYS_LOGSETTINGS);
		RegExpUtils regUtil = new RegExpUtils();
		LogSettings logSet = (LogSettings) regUtil.getMapValue(logSetsMap, uri
				+ op);
		if (null != logSet)
			insertLogInfo(request, session, logSet);
	}

	private void insertLogInfo(HttpServletRequest request, HttpSession session,
			LogSettings logSetting) {
		LogInfo logInfo = new LogInfo();
		logInfo.setLogDesc(logSetting.getLogDesc());
		logInfo.setLogLevel(logSetting.getLogLevel());
		logInfo.setLogDate(new Date());
		logInfo.setLogId(logSetting.getId());
		UserBean userBean = SystemUtil.getLoginUser();
		// UserInfo userInfo = userBean.getUserInfo();
		if (null != userBean.getGftUserInfo()) {
			logInfo.setEnterpriseId("111111111111111111111111");
			logInfo.setUserName(userBean.getGftUserInfo().getUserName());
		} else if (null != userBean.getGftUserInfo()) {
			logInfo.setEnterpriseId("gftadmin");
			logInfo.setUserName(userBean.getGftUserInfo().getUserName());
		}

		String[] templates = logSetting.getLogTemplate().split("###");
		if (0 < templates.length)
			logInfo.setLogContent(handleLog(templates, request));
		this.dao.saveObject(logInfo);
	}

	private String handleLog(String[] templates, HttpServletRequest request) {
		StringBuffer buf = new StringBuffer();
		String temp = "";
		for (int i = 0; i < templates.length; i++) {
			if ((i & 1) == 0) { // i为偶数
				buf.append(templates[i]);
			} else {
				if (templates[i].toLowerCase().startsWith("request_")) {
					temp = templates[i].replace("Request_", "");
					String s = request.getParameter(temp);
					buf.append(s);
				} else if (templates[i].toLowerCase().startsWith("session_")) {
					temp = templates[i].replace("Session_", "");
					buf.append(SystemUtil.getSessionValue(temp));
				}
			}
		}
		String content = buf.toString();
		if (null == content || "".equals(content))
			content = "无";
		return content;
	}

	public Map<String, List> initRightSettings() {
		log.debug("初始化RightSettings开始");
		List<RightSettings> rSettingList;
		Map<String, List> map = new HashMap<String, List>();
		for (Object obj : this.dao.listByHql("FROM RightSettings")) {
			RightSettings rs = (RightSettings) obj;
			if (null == map.get(rs.getUrl() + rs.getOp())) {
				rSettingList = new ArrayList<RightSettings>();
				rSettingList.add(rs);
				map.put(rs.getUrl() + rs.getOp(), rSettingList);
			} else {
				rSettingList = map.get(rs.getUrl() + rs.getOp());
				rSettingList.add(rs);
				map.put(rs.getUrl() + rs.getOp(), rSettingList);
			}
		}
		log.info("初始化RightSettings结束");
		return map;

	}

	public boolean inspectionRight(HttpServletRequest request,
			HttpSession session) {
		String uri = request.getRequestURI().replaceFirst(
				request.getContextPath(), "");
		String op = "";
		if (null != request.getParameter("op"))
			op = request.getParameter("op");

		RegExpUtils regUtil = new RegExpUtils();

		Map rightSettMap = (Map) session.getServletContext().getAttribute(
				Constants.SYS_RIGHTSETTINGS);
		UserBean userBean = (UserBean) session.getAttribute(Constants.USERBEAN);

		/*List<RightSettings> lr = regUtil.getMapValue(rightSettMap, uri + op);
		if (lr.size() < 1) {
			return true;
		} else {
			if (userBean != null) {
				Map rightMap = userBean.getGftRightMap();
				for (RightSettings rs : lr) {
					if (null != regUtil
							.getMapValue(rightMap, rs.getRightId()))
						return true;
				}
			}
		}*/

		return false;
	}

	/**
	 * 验证是否有用户没有用户加入一条
	 */
	public void initUser() {
		String HQL = "FROM GftUserInfo ";
		if(this.dao.getTotalCount(HQL)==0){
			GftUserInfo admin = new GftUserInfo();
			admin.setUserName("admin");
			admin.setUserType(Constants.USER_ADMIN);
			admin.setPassWord("admin");
			admin.setPosition("admin");
			admin.setRealName("shiming");
			admin.setStatus(Constants.STATUS_YES);
			this.dao.saveObject(admin);
		}
		
	}

}
